package com.link.play.fit.ai.ui.main

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.activity.addCallback
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewpager2.widget.ViewPager2
import androidx.work.WorkManager
import com.google.firebase.firestore.Filter
import com.google.gson.Gson
import com.link.play.fit.ai.GlobalConfig
import com.link.play.fit.ai.GlobalConfig.NOTIFICATION_EVENING_REMINDER
import com.link.play.fit.ai.GlobalConfig.NOTIFICATION_MEALS_EVENING_ID
import com.link.play.fit.ai.GlobalConfig.NOTIFICATION_MEALS_MORNING_ID
import com.link.play.fit.ai.GlobalConfig.NOTIFICATION_MEALS_NOON_ID
import com.link.play.fit.ai.GlobalConfig.NOTIFICATION_MORNING_REMINDER
import com.link.play.fit.ai.GlobalConfig.NOTIFICATION_NOON_REMINDER
import com.link.play.fit.ai.R
import com.link.play.fit.ai.RemoteConfig.vipNeedPlanPay
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.base.viewBind
import com.link.play.fit.ai.bean.CalendarStatusData
import com.link.play.fit.ai.bean.DesBean
import com.link.play.fit.ai.bean.ExerciseBean
import com.link.play.fit.ai.bean.ExerciseBean.Companion.getMET
import com.link.play.fit.ai.bean.LogWeightBean
import com.link.play.fit.ai.bean.MealsTimeData
import com.link.play.fit.ai.bean.NutritionBean
import com.link.play.fit.ai.bean.RecentlyEatenData
import com.link.play.fit.ai.bean.ScanBean
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.bean.checkFoodInfoBean
import com.link.play.fit.ai.bean.toRecentlyEatenData
import com.link.play.fit.ai.databinding.AcMainBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.kv.AuthCache
import com.link.play.fit.ai.kv.AuthCache.SUB_PRODUCT_TYPE
import com.link.play.fit.ai.kv.AuthCache.firstMeals
import com.link.play.fit.ai.kv.AuthCache.isBurnedSwitch
import com.link.play.fit.ai.kv.AuthCache.isInitGuide
import com.link.play.fit.ai.kv.AuthCache.isVip
import com.link.play.fit.ai.kv.AuthCache.mealsAlarmCount
import com.link.play.fit.ai.kv.AuthCache.pushCount
import com.link.play.fit.ai.kv.AuthCache.secondMeals
import com.link.play.fit.ai.kv.AuthCache.thirdMeals
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_CALENDAR_STATUS_LIST_DATA_KEY
import com.link.play.fit.ai.store.CloudStore.DOC_LOG_WEIGHT
import com.link.play.fit.ai.store.CloudStore.DOC_MEALS_TIME_LIST_DATA
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.ui.dialog.HomeMenuDialog
import com.link.play.fit.ai.ui.exercise.LogExerciseAc
import com.link.play.fit.ai.ui.main.adapter.HomeChildAdapter
import com.link.play.fit.ai.ui.main.foodDatabase.FoodDatabaseAc
import com.link.play.fit.ai.ui.main.fragment.AnalyticsFg
import com.link.play.fit.ai.ui.main.fragment.ControlFg
import com.link.play.fit.ai.ui.main.fragment.HomeFg
import com.link.play.fit.ai.ui.main.saveFood.SaveFoodAc
import com.link.play.fit.ai.ui.scanFood.ScanFoodAc
import com.link.play.fit.ai.ui.scanFood.ScanGuideAc
import com.link.play.fit.ai.ui.vip.VipFreeAc
import com.link.play.fit.ai.utils.DailyFirstLaunchUtil.isFirstExerciseToday
import com.link.play.fit.ai.utils.DailyScheduleManager.scheduleTask
import com.link.play.fit.ai.utils.DateEx.getCurrentDayOfMonth
import com.link.play.fit.ai.utils.DateEx.getDayOfMonth
import com.link.play.fit.ai.utils.FileUtils.stringUriToFile
import com.link.play.fit.ai.utils.NotifycationUtils.scheduleDrinkingReminders
import com.link.play.fit.ai.utils.NotifycationUtils.scheduleWeeklyPush
import com.link.play.fit.ai.utils.NotifycationUtils.startPeriodicPushes
import com.link.play.fit.ai.utils.TimeUtils.calculateEndDate
import com.link.play.fit.ai.utils.TimeUtils.isAverageAfter1130AM
import com.link.play.fit.ai.utils.getExerciseCal
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import kotlin.math.roundToInt


class MainAc : BaseActivity<AcMainBinding>(AcMainBinding::inflate) {
    private var userGuide: UserGuide? = null
    private var calendarStatusDataList: MutableList<CalendarStatusData> = mutableListOf()
    private var mealsTime: List<String> = listOf()
    private val controlFg by lazy(LazyThreadSafetyMode.NONE) {
        ControlFg()
    }
    private val homeFg by lazy(LazyThreadSafetyMode.NONE) {
        HomeFg()
    }
    private val analyticaFg by lazy(LazyThreadSafetyMode.NONE) {
        AnalyticsFg()
    }

    //    private val settingFg by lazy(LazyThreadSafetyMode.NONE) {
//        SettingsFg()
//    }
    private val fragmentList: List<Fragment> by lazy(LazyThreadSafetyMode.NONE) {
        mutableListOf(
            homeFg,
            controlFg,
            analyticaFg
        )
    }

    val viewModel: MainViewModel by lazy {
        ViewModelProvider(this)[MainViewModel::class.java]
    }
    private val baseViewModel: GlobalViewModel by lazy {
        GlobalViewModel.getInstance(application)
    }
    private val homeMenuDialog by lazy {
        this.let { k ->
            HomeMenuDialog(k, {
                when (it) {
                    1 -> {  // Log Exercise
                        goToAc(LogExerciseAc::class.java)
                    }

                    2 -> {  // Saved foods

                        goToAc(SaveFoodAc::class.java) {
                            putExtra(
                                "bean",
                                viewModel.getDateList()[viewModel.getCalendarPosition()]
                            )
                        }
                    }

                    3 -> {  //  Food Database
                        goToAc(FoodDatabaseAc::class.java)

                    }

                    4 -> {  // Scan Food
                        if (!AuthCache.isScanGuided) {
                            AuthCache.isScanGuided = true
                            goToAc(ScanGuideAc::class.java)
                        } else {
                            goToAc(ScanFoodAc::class.java)
                        }
                    }
                }
            }).builder()
        }
    }
    private var lastBackPressTime = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        init()
        intentData()
        initListener()
        pressToExit()
        observerRequest()

        EventBus.getDefault().register(this)

        startPeriodicPushes(this, pushCount)
        scheduleDailyNotifications()
        scheduleWeeklyPush(this)
        scheduleDrinkingReminders(this)

//        CongratulationDialog(this).showDialog()
//        goToAc(RuleAc::class.java)
    }

    private fun intentData() {
        lifecycleScope.launch(CoroutineExceptionHandler { _, _ ->  }) {
            userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
            "userGuide  $userGuide".d()
            val userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
            userGuide?.let {
                viewModel.setData(it)
                if (!isInitGuide) {
                    val calendarData = CalendarStatusData().apply {
                        timeDate = getDayOfMonth()
                        caloriesDaily = it.caloriesDaily
                        carbsDaily = it.carbsDaily
                        proteinDaily = it.proteinDaily
                        fatsDaily = it.fatsDaily
                    }
                    viewModel.saveCalendarListData(calendarData)
                }
                mealsTime = it.mealsTime
                if(vipNeedPlanPay){
//                    homeFg.isShowNg(it.isAppPurchaseVip)
                    controlFg.isShowNg(it.isAppPurchaseVip)

                }else{
//                    homeFg.isShowNg(!isVip)
                    controlFg.isShowNg(!isVip)

                }

            }
            calendarStatusDataList = (CloudStore.getList<CalendarStatusData>(
                CloudStore.DOC_CALENDAR_STATUS_LIST_DATA,
                DOC_CALENDAR_STATUS_LIST_DATA_KEY
            ) as MutableList<CalendarStatusData>)
            if (calendarStatusDataList.isEmpty()) {
                userGuide?.let {
                    val calendarData = CalendarStatusData().apply {
                        timeDate = getCurrentDayOfMonth()
                        caloriesDaily = it.caloriesDaily
                        carbsDaily = it.carbsDaily
                        proteinDaily = it.proteinDaily
                        fatsDaily = it.fatsDaily
                    }
                    calendarStatusDataList.add(calendarData)
                    viewModel.saveCalendarListData(calendarData)
                }
            }
            homeFg.setListData(calendarStatusDataList)
            "calendarStatusDataList  $calendarStatusDataList".d()
        }

    }


    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        lifecycleScope.launch {
            val run = intent.extras?.getString("Exercise")
            val exerciseBean: ExerciseBean? = Gson().fromJson(run, ExerciseBean::class.java)
            //计算卡路里
            val kg = CloudStore.getListItem<LogWeightBean>(
                DOC_LOG_WEIGHT,
                DOC_LOG_WEIGHT,
                Filter.lessThanOrEqualTo(
                    "createTime",
                    System.currentTimeMillis()
                )
            )?.weightKg ?: userGuide?.weightKg ?: 0
            exerciseBean?.let {
                it.cal = getExerciseCal(it.getMET(), kg, it.time.toFloat() / 60f)
            }
            Log.e(TAG, "kg=$kg exerciseBean=$exerciseBean")
            "kg=$kg exerciseBean=$exerciseBean".d()
            exerciseBean?.let {
                val bean = RecentlyEatenData().apply {
                    caloriesDaily = it.cal
                    type = 1  //运动
                    showType = if (it.type == 3) 2 else 1
                    typeChild = it.type
                    intensityPercent = it.intensityPercent
                    timeDay = viewModel.getTimeDay()
                    time = it.time
                    describe = it.describe
                    isBurnedSwitchV = isBurnedSwitch
                    createTime = System.currentTimeMillis().toString()
                }
                val p = viewModel.getCalendarPosition()
                val list = viewModel.getDateList()
                if (isBurnedSwitch) {
                    list[p].caloriesDaily += it.cal
                    list[p].exerciseCaloriesDaily += it.cal
                    homeFg.putListData(list[p], isFirstExerciseToday(this@MainAc), isAdjust = true)
                }
                "bean  $bean".d()
                viewModel.putCalendarListData(oldData = list[p])
                homeFg.addRecentlyList(bean)
                if (it.type == 3) {
                    val weightKg = if (userGuide != null) {
                        userGuide!!.weightKg
                    } else {
                        70
                    }
                    viewModel.byDescribe(
                        DesBean(description = it.describe, weight = weightKg),
                        bean.createTime
                    )
                } else {
                    viewModel.saveRecentlyData(bean)
                }
            }

            //拍照食物
            val scanBeanS = intent.extras?.getString("ScanBean")
            scanBeanS?.let {
                val scanBean: ScanBean? = Gson().fromJson(scanBeanS, ScanBean::class.java)
                "scanBean  $scanBean".d()
                scanBean?.let { an ->
                    val bean = RecentlyEatenData().apply {
                        type = 2 //扫描食物
                        typeChild = an.type
                        showType = 2
                        timeDay = viewModel.getTimeDay()
                        img = an.imagePathOrUri
                        barcode = an.barcode
                        barcodeType = an.barcodeType
                        createTime = System.currentTimeMillis().toString()
                    }
                    homeFg.addRecentlyList(bean)
                    val file = when (bean.typeChild) {
                        3 -> {
                            stringUriToFile(this@MainAc, an.imagePathOrUri)
                        }
                        else -> {
                            File(an.imagePathOrUri)
                        }
                    }
                    runCatching {
                        when (bean.typeChild) {
                            0, 3 -> { // food scan
                                viewModel.scanFood(file!!, bean.createTime, bean)
                            }

                            1 -> { // barcode
                                viewModel.barcode(file!!, bean.createTime, bean)
                            }

                            2 -> { // food label
                                viewModel.label(file!!, bean.createTime, bean)
                            }
                        }
                    }
                }
            }

            //data Base
            val logFood = intent.extras?.getString("logFood")
            logFood?.let { k ->
                val foodBean: RecentlyEatenData? =
                    Gson().fromJson(logFood, RecentlyEatenData::class.java)
                "logFood  $foodBean  ${foodBean?.caloriesDaily}".d()
                foodBean?.let {
                    homeFg.addRecentlyList(it)
                    updateCalendarAndRecently(it)
//                    //更新日历
//                    val p = viewModel.getCalendarPosition()
//                    val list = viewModel.getDateList()
//                    if (it.checkFoodInfoBean()){
//                        list[p].consumeCaloriesDaily += (it.caloriesDaily * it.servings).roundToInt()
//                        list[p].consumeCarbsDaily += (it.carbsDaily * it.servings).roundToInt()
//                        list[p].consumeProteinDaily += (it.proteinDaily * it.servings).roundToInt()
//                        list[p].consumeFatsDaily += (it.fatsDaily * it.servings).roundToInt()
//                    }else{
//                        list[p].consumeCaloriesDaily += it.caloriesDaily
//                        list[p].consumeCarbsDaily += it.carbsDaily
//                        list[p].consumeProteinDaily += it.proteinDaily
//                        list[p].consumeFatsDaily += it.fatsDaily
//                    }
//                    viewModel.putCalendarListData(oldData = list[p])
//                    homeFg.putListData(list[p], isFirstExerciseToday(this@MainAc))
                }
            }
            // data base ai 生成的食物
            val foodName = intent.extras?.getString(FoodDatabaseAc.AiFood)
            foodName?.let {
                val bean = RecentlyEatenData().apply {
                    type = 4 //ai食物
                    showType = 2 // 加载中
                    timeDay = viewModel.getTimeDay() //当天的时间
                    createTime = System.currentTimeMillis().toString()
                }
                homeFg.addRecentlyList(bean)
                viewModel.getAiFoodInfo(foodName, bean.createTime, bean)
            }

            val controlType = intent.extras?.getString("controlType") //健身计划
            controlType?.let {
                when (it) {
                    "startPlan" -> {
                        binding.vpMain.currentItem = 1
                        choseMenu(1)
//                        binding.bottomNav.menu.getItem(1).setChecked(true)
                        controlFg.showData()
//                        homeFg.toPlanUpdateData()
                        val p = viewModel.getCalendarPosition()
                        val list = viewModel.getDateList()
                        homeFg.updateUserTarget(list[p])
                        lifecycleScope.launch {
                            val user = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
                            user?.let { k ->
                                controlFg.isShowNg(k.isAppPurchaseVip)
                            }
                        }

                    }

                    "backMain" -> {
                        binding.vpMain.currentItem = 1
                        choseMenu(1)

//                        binding.bottomNav.menu.getItem(1).setChecked(true)
                        controlFg.showData()
                    }
                }
            }
        }
    }

    /**
     * 更新每日列表和日历
     */
    private fun updateCalendarAndRecently(recentlyEatenData:RecentlyEatenData?=null,nutritionBean: NutritionBean?=null){

        val p = viewModel.getCalendarPosition()
        val list = viewModel.getDateList()
        recentlyEatenData?.let {
            if (it.checkFoodInfoBean()){
                list[p].consumeCaloriesDaily += (it.caloriesDaily * it.servings).roundToInt()
                list[p].consumeCarbsDaily += (it.carbsDaily * it.servings).roundToInt()
                list[p].consumeProteinDaily += (it.proteinDaily * it.servings).roundToInt()
                list[p].consumeFatsDaily += (it.fatsDaily * it.servings).roundToInt()
            }else{
                list[p].consumeCaloriesDaily += it.caloriesDaily
                list[p].consumeCarbsDaily += it.carbsDaily
                list[p].consumeProteinDaily += it.proteinDaily
                list[p].consumeFatsDaily += it.fatsDaily
            }
        }
        nutritionBean?.let {
            list[p].consumeCaloriesDaily += it.caloriesKcal
            list[p].consumeCarbsDaily += it.carbsG
            list[p].consumeProteinDaily += it.proteinG
            list[p].consumeFatsDaily += it.fatsG
        }
        viewModel.putCalendarListData(list[p])
        homeFg.putListData(list[p], isFirstExerciseToday(this@MainAc))

    }

    private fun observerRequest() {
        lifecycleScope.launch {
            baseViewModel.recentlyEatenDataFlow.collect { bean ->  //扫描食物
                "bean baseViewModel $bean ".d()
                when (bean.notifyType) {
                    //1 添加 , 2 是删除, 3是更新
                    1 -> {
                        homeFg.addRecentlyList(bean)
                        updateCalendarAndRecently(recentlyEatenData = bean)
//                        bean.let {
//                            val p = viewModel.getCalendarPosition()
//                            val list = viewModel.getDateList()
//                            list[p].consumeCaloriesDaily += (it.caloriesDaily * it.servings).roundToInt()
//                            list[p].consumeCarbsDaily += (it.carbsDaily * it.servings).roundToInt()
//                            list[p].consumeProteinDaily += (it.proteinDaily * it.servings).roundToInt()
//                            list[p].consumeFatsDaily += (it.fatsDaily * it.servings).roundToInt()
//                            homeFg.putListData(list[p], isFirstExerciseToday(this@MainAc))
//                            viewModel.putCalendarListData(list[p])
//                        }
                    }

                    2 -> {
                        homeFg.deleteRecentlyList(bean)
                        bean.let {
                            val p = viewModel.getCalendarPosition()
                            val list = viewModel.getDateList()

                            list[p].consumeCaloriesDaily -= (it.caloriesDaily * it.servings).roundToInt()
                            list[p].consumeCarbsDaily -= (it.carbsDaily * it.servings).roundToInt()
                            list[p].consumeProteinDaily -= (it.proteinDaily * it.servings).roundToInt()
                            list[p].consumeFatsDaily -= (it.fatsDaily * it.servings).roundToInt()

                            homeFg.putListData(list[p], isFirstExerciseToday(this@MainAc))
                            viewModel.putCalendarListData(list[p])
                        }
                    }

                    3 -> {
                        homeFg.updateRecentlyList(bean)
//                        bean.let {
//                            val p = viewModel.getCalendarPosition()
//                            val list =  viewModel.getDateList()
//                            list[p].consumeCaloriesDaily += (it.caloriesDaily*it.servings).roundToInt()
//                            list[p].consumeCarbsDaily += (it.carbsDaily*it.servings).roundToInt()
//                            list[p].consumeProteinDaily += (it.proteinDaily*it.servings).roundToInt()
//                            list[p].consumeFatsDaily += (it.fatsDaily*it.servings).roundToInt()
//                            homeFg.putListData(list[p], isFirstExerciseToday(this@MainAc))
//                        }
                    }
                }
            }
        }

        viewModel.message.observe(this, {
            when (it) {
                "scanAgain" -> {
                    goToAc(ScanGuideAc::class.java)
                }

                "toJournal" -> {
                    binding.vpMain.currentItem = 1
                    choseMenu(1)

//                    binding.bottomNav.menu.getItem(1).setChecked(true)
                }
            }
        })


        lifecycleScope.launch {
                viewModel.foodBeanFlow.collect { bean ->  //扫描食物
                    if (bean?.status == -1) return@collect
                    bean?.let { data ->
                        "response bean  $data".d()
                        homeFg.notifyRecentlyScanLoadItem(data.scanFoodBean, data.timeId)

                        data.scanFoodBean?.nutrition?.let {
                            updateCalendarAndRecently(nutritionBean = it)
                        }
                    }
                }
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.foodInfoLiveData.collect { bean ->  //food database Ai 生成的食物
                    if (bean.status == -1) return@collect
                    runCatching {
                        if (bean.status == 200) {
                            val ingredientBean = bean.aiFoodInfo?.ingredients?.first()
                            ingredientBean?.toRecentlyEatenData()?.apply {
                                createTime = bean.timeId
                                homeFg.updateRecentlyList(this)
                                ingredientBean.timeMillisencond = createTime
                                //添加到最近添加的列表
                                CloudStore.addToList(
                                    CloudStore.DOC_FOOD_DATABASE_RECENTLY_DATA,
                                    CloudStore.DOC_FOOD_DATABASE_RECENTLY_DATA,
                                    bean.timeId,
                                    bean.aiFoodInfo!!
                                )
                                updateCalendarAndRecently(recentlyEatenData = this)
                            }
                        } else {
                            bean.recentlyEatenData?.apply {
                                showType = 3
                                homeFg.updateRecentlyList(bean.recentlyEatenData!!)
                            }
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            viewModel.desFixLiveBean.collect { bean ->  //扫描食物
                if (bean?.status == -1) return@collect
                if (bean?.byDesFixBean == null) return@collect
                "response desFixLiveBean  ${bean.byDesFixBean}".d()
                val weight = userGuide?.weightKg ?: 0
                bean.byDesFixBean?.let {
                    homeFg.notifyRecentlyByDes(it, bean.timeId, weight)
                }
            }
        }
    }


    @SuppressLint("ClickableViewAccessibility")
    private fun initListener() {
//        binding.bottomNav.setOnItemSelectedListener { item: MenuItem ->
//            when (item.itemId) {
//                R.id.nav_home -> {
//                    binding.vpMain.currentItem = 0
//                }
//                R.id.nav_control -> {
//                    binding.vpMain.currentItem = 1
//                }
//                R.id.nav_search -> {
//                    binding.vpMain.currentItem = 2
//                }
////                R.id.nav_profile -> {
////                    binding.vpMain.currentItem = 3
////                }
//            }
//            false
//        }
        binding.vpMain.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
//                binding.bottomNav.menu.getItem(position).setChecked(true)
                binding.draggableImage.isVisible = position != 1

            }
        })

        binding.draggableImage.setOnClickListener {
            if (isVip) {
                homeMenuDialog.show()
            } else {
                goToAc(VipFreeAc::class.java)
            }
        }
    }

    override fun useDefaultImmersive() {
        super.useDefaultImmersive()
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }


    private fun pressToExit() {
        onBackPressedDispatcher.addCallback {
            val currentTIme = System.currentTimeMillis()
            if (currentTIme - lastBackPressTime >= 2000) {
                // 显示提示信息
                Toast.makeText(this@MainAc, getString(R.string.press_again), Toast.LENGTH_SHORT)
                    .show()
                // 记录时间
                lastBackPressTime = currentTIme
            } else {
                //退出应用
                finish()
            }
        }
    }

    private fun init(){
        viewBind {
            vpMain.adapter =
                HomeChildAdapter(supportFragmentManager, lifecycle, fragmentList)
//            vpMain.adapter = MainFgAdapter(supportFragmentManager, lifecycle)
            vpMain.getChildAt(0).overScrollMode = View.OVER_SCROLL_NEVER
            vpMain.offscreenPageLimit = 3
            vpMain.isUserInputEnabled = false
            binding.vpMain.setCurrentItem(0, false)
//            binding.bottomNav.menu.getItem(0).setChecked(true)

            bottomLayout.journalLayout.setOnClickListener {
                choseMenu(0)
            }
            bottomLayout.coachLayout.setOnClickListener {
                choseMenu(1)

            }
            bottomLayout.analyticsLayout.setOnClickListener {
                choseMenu(2)

            }

        }
        lifecycleScope.launch {
            //更新公英制
            GlobalConfig.imperialMetricFlow.collectLatest {
                AuthCache.imperialMetric = it
            }
        }
    }

    private fun choseMenu(p:Int) = with(binding){
        when(p){
            0 ->{

                binding.vpMain.setCurrentItem(0, true)
                bottomLayout.journalImg.setImageResource(R.mipmap.icon_home_yixuan_new)
                bottomLayout.journalText.setTextColor(getColor(R.color.color_17CB81))

                bottomLayout.coachImg.setImageResource(R.mipmap.icon_coach_new_weixuan)
                bottomLayout.coachText.setTextColor(getColor(R.color.color_DBDBDB))
                bottomLayout.analyticsImg.setImageResource(R.mipmap.analytics_no_chose_icon)
                bottomLayout.analyticsText.setTextColor(getColor(R.color.color_DBDBDB))
            }
            1 ->{
                binding.vpMain.setCurrentItem(1, true)
                bottomLayout.journalImg.setImageResource(R.mipmap.icon_home_weixuan)
                bottomLayout.journalText.setTextColor(getColor(R.color.color_DBDBDB))

                bottomLayout.coachImg.setImageResource(R.mipmap.icon_coach_new_yixuan)
                bottomLayout.coachText.setTextColor(getColor(R.color.color_17CB81))
                bottomLayout.analyticsImg.setImageResource(R.mipmap.analytics_no_chose_icon)
                bottomLayout.analyticsText.setTextColor(getColor(R.color.color_DBDBDB))

            }
            2 ->{
                binding.vpMain.setCurrentItem(2, true)
                bottomLayout.journalImg.setImageResource(R.mipmap.icon_home_weixuan)
                bottomLayout.journalText.setTextColor(getColor(R.color.color_DBDBDB))
                bottomLayout.coachImg.setImageResource(R.mipmap.icon_coach_new_weixuan)
                bottomLayout.coachText.setTextColor(getColor(R.color.color_DBDBDB))
                bottomLayout.analyticsImg.setImageResource(R.mipmap.analytics_chose_icon)
                bottomLayout.analyticsText.setTextColor(getColor(R.color.color_17CB81))
            }
        }
    }


    //设置早中晚餐推送
    private fun scheduleDailyNotifications() {
        if (isVip) {
            // 定义三个目标时间点（早、中、晚）
            val morningTime = firstMeals.ifEmpty {
                "8:30:AM"
            }

            val eveningTime = thirdMeals.ifEmpty {
                "6:30:PM"
            }
            var noonTime: String
            val list: MutableList<String> = mutableListOf()
            if (mealsAlarmCount >= 10) {
                lifecycleScope.launch {
                    val mealsList = CloudStore.getList<MealsTimeData>(
                        DOC_MEALS_TIME_LIST_DATA,
                        DOC_MEALS_TIME_LIST_DATA
                    ) as MutableList<MealsTimeData>
                    val timeList: MutableList<String> = mutableListOf()
                    mealsList.forEach {
                        timeList.add(it.value)
                    }

                    noonTime = if (timeList.isNotEmpty()) {
                        if (isAverageAfter1130AM(timeList)) {
                            "3:00:PM"
                        } else {
                            "11:30:AM"
                        }
                    } else {
                        "11:30:AM"
                    }
                    if (noonTime.isNotEmpty()) {
                        list.add(noonTime)
                    }
                    "$morningTime  $noonTime  $eveningTime  ".d()
                    scheduleTask(NOTIFICATION_NOON_REMINDER, noonTime,"$NOTIFICATION_MEALS_NOON_ID")
                }
            } else {
                if (secondMeals.isNotEmpty()) {
                    scheduleTask(NOTIFICATION_NOON_REMINDER, secondMeals,"$NOTIFICATION_MEALS_NOON_ID")
                }
            }
            "firstMeals:$firstMeals secondMeals:$secondMeals thirdMeals:$thirdMeals".d()
            scheduleTask(NOTIFICATION_MORNING_REMINDER, morningTime,"$NOTIFICATION_MEALS_MORNING_ID")
            scheduleTask(NOTIFICATION_EVENING_REMINDER, eveningTime,"$NOTIFICATION_MEALS_EVENING_ID")
        } else {
            WorkManager.getInstance(this).cancelUniqueWork(NOTIFICATION_NOON_REMINDER)
            WorkManager.getInstance(this).cancelUniqueWork(NOTIFICATION_MORNING_REMINDER)
            WorkManager.getInstance(this).cancelUniqueWork(NOTIFICATION_EVENING_REMINDER)
        }

    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: String) {
        "onMessageEvent $event".d()
        when (event) {
            "isVip" -> {
                homeFg.isShowRecentlyList()
                lifecycleScope.launch {
                    val user = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
                    user?.let {
                        if(vipNeedPlanPay){
//                            homeFg.isShowNg(it.isAppPurchaseVip)
                            controlFg.isShowNg(it.isAppPurchaseVip)

                        }else{
//                            homeFg.isShowNg(!isVip)
                            controlFg.isShowNg(!isVip)

                        }
                    }
                }
            }

            "flushMain" -> {
                binding.vpMain.currentItem = 1
                choseMenu(1)
//                binding.bottomNav.menu.getItem(1).setChecked(true)
                controlFg.showData()
                lifecycleScope.launch {
                    val user = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
                    user?.let {
                        if(vipNeedPlanPay){
//                            homeFg.isShowNg(it.isAppPurchaseVip)
                            controlFg.isShowNg(it.isAppPurchaseVip)

                        }else{
//                            homeFg.isShowNg(!isVip)
                            controlFg.isShowNg(!isVip)

                        }
                    }
                }
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}